package com.zzz.robot201.service.client;

public class CommonBytes {
    /**
     * 将int转为低字节在前，高字节在后的byte数组
     */
    public static byte[] tolh(int n) {
        byte[] b = new byte[4];
        b[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
        b[2] = (byte) (n >> 16 & 0xff);
        b[3] = (byte) (n >> 24 & 0xff);
        return b;
    }
    /**
     * 将byte数组转化成String
     */
    public static String toStr(byte[] valArr,int maxLen) {
        int index = 0;
        while(index < valArr.length && index < maxLen) {
            if(valArr[index] == 0) {
                break;
            }
            index++;
        }
        byte[] temp = new byte[index];
        System.arraycopy(valArr, 0, temp, 0, index);
        return new String(temp);
    }

    /**
     * 将低字节在前转为int，高字节在后的byte数组
     */
    public static int vtolh(byte[] bArr) {
        int n = 0;
        for(int i=0;i<bArr.length&&i<4;i++){
            int left = i*8;
            n+= (bArr[i] << left);
        }
        return n;
    }

    /**
     * 将float转为低字节在前，高字节在后的byte数组
     */
    public static byte[] tolh(float f) {
        return tolh(Float.floatToRawIntBits(f));
    }

    public static float getFloat(byte[] b) {
        int accum = 0;
        accum = accum|(b[0] & 0xff) << 0;
        accum = accum|(b[1] & 0xff) << 8;
        accum = accum|(b[2] & 0xff) << 16;
        accum = accum|(b[3] & 0xff) << 24;
        return Float.intBitsToFloat(accum);
    }

    public static short[] toShortArray(byte[] src) {
        int count = src.length >> 1;
        short[] dest = new short[count];
        for (int i = 0; i < count; i++) {
            dest[i] = (short) (src[i * 2] << 4 | src[2 * i + 1] & 0xff);
        }
        return dest;
    }

    // 大字节转为小字节,解析
    public static short byteToShort_HL(byte[] b){
        return (short)((((b[1]) << 8) & 0xff00 | b[0] & 0x00ff));
    }
    // 小字节转为大字节,组装
    public static void shortToByte_LH(short shortVal, byte[] b, int offset) {
        b[0 + offset] = (byte) (shortVal & 0xff);
        b[1 + offset] = (byte) (shortVal >> 8 & 0xff);
    }

    public static void intToByte_LH(int intVal, byte[] b, int offset) {
        b[0 + offset] = (byte) (intVal & 0xff);
        b[1 + offset] = (byte) (intVal >> 8 & 0xff);
        b[2 + offset] = (byte) (intVal >> 16 & 0xff);
        b[3 + offset] = (byte) (intVal >> 24 & 0xff);
    }

    public static int byteToInt_HL(byte[] b, int offset) {
        int result;
        result = (((b[3 + offset] & 0x00ff) << 24) & 0xff000000)
                | (((b[2 + offset] & 0x00ff) << 16) & 0x00ff0000)
                | (((b[1 + offset] & 0x00ff) << 8) & 0x0000ff00)
                | ((b[0 + offset] & 0x00ff));
        return result;
    }

}
